﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Xml;
using UnityEngine.SceneManagement;


public class Diverse : MonoBehaviour
{
    public Button enterBtn;//提交
    public Text properText;//答对数量文本
    public Text goldText;//显示金币文本（金币）
    public Text expText;//显示经验文本（经验）

    public RectTransform quesParent;//问题的父类
    public GameObject quesPrefab;//问题预制体
    const int height = 150;

    List<Ques> quesList = new List<Ques>();//结构体列表

    struct Ques
    {
        public string ques;//问题
        public string ansA;//答案A
        public string ansB;//答案B
        public string ansC;//答案C
        public string ansD;//答案D
        public string answer;//正确答案
        public string myAnswer;//答题答案
    }

    // Start is called before the first frame update
    void Start()
    {
        MySqlAccess.gold = MySqlAccess.QueryGold();
        MySqlAccess.exp = MySqlAccess.QueryExp();
        //在XML中读取问题
        LoadQues();
        //生成问题
        SpawnQues();
        //提交
        enterBtn.onClick.AddListener(delegate
        {
            ButtonSubmit();
            GameObject.Find("Canvas").transform.Find("面板").gameObject.SetActive(true);
        });
        GameObject.Find("Canvas").transform.Find("面板/确定").GetComponent<Button>().onClick.AddListener(delegate
        {
            SceneManager.LoadScene("LeftBrain");
        });
    }

    //读取题目
    void LoadQues()
    {
        //为XML文档开辟内存
        XmlDocument xmlDoc = new XmlDocument();
        //将XML转换为文本资源
        TextAsset textAsset = (TextAsset)Resources.Load("Qus");
        xmlDoc.LoadXml(textAsset.ToString().Trim());

        //XML元素根节点
        XmlElement root = xmlDoc.DocumentElement;
        //子节点
        int rd =Random.Range(1,11);//随机数
        XmlElement node = (XmlElement)root.SelectSingleNode("Question"+rd);
        //将子节点放入XML子节列表中
        XmlNodeList list = node.ChildNodes;
        //遍历子节点列表
        foreach (XmlElement x in list)
        {
            //为结构体开辟内存
            Ques qus = new Ques();
            qus.ques = x.GetAttribute("question");
            qus.ansA = x.GetAttribute("A");
            qus.ansB = x.GetAttribute("B");
            qus.ansC = x.GetAttribute("C");
            qus.ansD = x.GetAttribute("D");
            qus.answer = x.GetAttribute("answer");
            qus.myAnswer = "";
            quesList.Add(qus);
        }
    }

    //生成题目
    void SpawnQues()
    {
        //动态的设置UI大小
        quesParent.sizeDelta = new Vector2(780, height * quesList.Count);
        for (int i = 0; i < quesList.Count; i++)
        {
            GameObject go = Instantiate(quesPrefab, quesParent);
            SetQuesInfo(go.transform, i);
        }
    }

    //设置问题的初始化信息
    void SetQuesInfo(Transform t, int idx)
    {
        int num = idx;
        Ques q = quesList[num];
        t.Find("Text").GetComponent<Text>().text = q.ques;
        t.Find("A").GetComponentInChildren<Text>().text = " A. " + q.ansA;
        t.Find("B").GetComponentInChildren<Text>().text = " B. " + q.ansB;
        t.Find("C").GetComponentInChildren<Text>().text = " C. " + q.ansC;
        t.Find("D").GetComponentInChildren<Text>().text = " D. " + q.ansD;

        //为按钮添加监听
        SetToggleListen(t, "A", num);
        SetToggleListen(t, "B", num);
        SetToggleListen(t, "C", num);
        SetToggleListen(t, "D", num);
    }

    //为Toggle按钮添加监听
    void SetToggleListen(Transform t, string s, int num)
    {
        t.Find(s).GetComponent<Toggle>().onValueChanged.AddListener(delegate (bool b)
        {
            if (b)
            {
                Ques q = quesList[num];
                q.myAnswer = s;
                quesList[num] = q;
            }
        });
    }

    //提交
    void ButtonSubmit()
    {
        int totalGold = 0;//总金币
        int totalExp = 0;//总经验
        int properNum = 0;//答对的数量
        int pointEveryQues = 10 / quesList.Count;//每道题的分数(金币，经验)

        foreach (Ques q in quesList)
        {
            if (q.myAnswer == q.answer)
            {
                totalGold += pointEveryQues * 10;//金币
                totalExp += pointEveryQues * 5;//经验
                properNum++;
            }
        }
        goldText.text = "获得金币：" + totalGold;
        MySqlAccess.gold += totalGold;
        MySqlAccess.UpdateInto("shop", new string[] { "gold" }, new string[] { MySqlAccess.gold.ToString() }, "id", LoginPanel.Showtetx());
        expText.text = "获得经验：" + totalExp;
        MySqlAccess.exp += totalExp;
        MySqlAccess.UpdateInto("player", new string[] { "exp" }, new string[] { MySqlAccess.exp.ToString() }, "id", LoginPanel.Showtetx());
        if (MySqlAccess.QueryExp() >= 100)
        {
            MySqlAccess.exp -= 100;
            MySqlAccess.UpdateInto("player", new string[] { "exp" }, new string[] { MySqlAccess.exp.ToString() }, "id", LoginPanel.Showtetx());
            MySqlAccess.level += 1;
            MySqlAccess.UpdateInto("player", new string[] { "level" }, new string[] { MySqlAccess.level.ToString() }, "id", LoginPanel.Showtetx());
        }
        properText.text = "答对数量：" + properNum;
    }
}
